﻿using System.Management.Automation;
using NETWORKLIST;

namespace BSonPosh.Network
{

	[Cmdlet(VerbsCommon.Get, "Network", SupportsShouldProcess = false)]
	public class GetNetworkCommand : PSCmdlet
	{

        private string[] _name = new[]{"*"};
        private NetworkCategory _category = NetworkCategory.Any;

        [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public string[] Name 
        {
            get { return _name; } 
            set { _name = value; } 
        }

        [Parameter()]
        public NetworkCategory Category 
        {
            get { return _category; } 
            set { _category = value; } 
        }

        [Parameter()]
        public SwitchParameter Force { get; set; }

        protected override void ProcessRecord()
		{
            base.ProcessRecord();

			using (var manager = new NLM())
			{
				IEnumNetworks networks = manager.Manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_ALL);

				foreach (INetwork item in networks)
				{
                    // Create NetworkInfo Object
                    NetworkInfo network = new NetworkInfo(item);

                    // Check for Category
                    if (_category != NetworkCategory.Any && _category != network.Category)
                    {
                        continue;
                    }

                    // Check for Name parameter
                    foreach (var n in Name)
                    {
                        
                        if ((new WildcardPattern(n, WildcardOptions.IgnoreCase)).IsMatch(network.Name))
                        {
                            if (Force)
                            {
                                WriteObject(network);
                            }
                            else if (n != "*")
                            {
                                WriteObject(network);
                            }
                            else
                            {
                                if (network.Connectivity != Connectivity.Disconnected)
                                {
                                    WriteObject(network);
                                }
                            }
                            break;
                        }
                    }
   				}
			}
		}
	}
}